<?php
namespace app\api\logic;

use app\api\cache\CarefreeCache;
use app\api\consDir\ErrorConst;
use app\api\consDir\OrderPrefixConst;
use app\api\consDir\SandConst;
use app\api\services\CarefreeInfoService;
use app\api\services\CarefreeOrderService;
use app\api\services\CartService;
use app\api\services\CouponService;
use app\api\services\MemberService;
use app\api\services\OrderService;
use app\api\services\PayService;
use app\api\services\SandService;
use app\api\services\ShopService;
use app\common\libs\Singleton;
use app\common\models\Carefree\CarefreeConfig;
use app\common\models\Carefree\CarefreeDeductionAmountLog;
use app\common\models\Carefree\CarefreeDividendAmountLog;
use app\common\models\Carefree\CarefreeMemberFinance;
use app\common\models\Carefree\CarefreeOrder;
use app\common\models\Carefree\CarefreeOrderGoods;
use app\common\models\Carefree\CarefreeProfitPoolLog;
use app\common\models\Carefree\CarefreeRedAmountLog;
use app\common\models\Carefree\CarefreeScoreAmountLog;
use app\common\models\Carefree\CarefreeSpeedAmountLog;
use app\common\models\Carefree\CarefreeWithdraw;
use app\common\models\CouponMember;
use app\common\models\Member\Member;
use app\common\models\Order\Order;
use app\common\models\Order\OrderAddress;
use app\common\models\Order\OrderGoods;
use app\common\models\Order\OrderShop;
use app\common\models\Service\Service;
use app\common\models\Shop\Shop;
use app\common\utils\CommonUtil;
use app\common\utils\RedLock;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

/**
 * 订单模块
 * Class MemberLogic
 * @package app\api\logic
 */
class CarefreeInfoLogic extends BaseLogic
{
    use Singleton;


    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function info(): array
    {
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')],
        ];
        $dayScore = CarefreeScoreAmountLog::getInstance()->where($where)->sum('amount') ?: '0.0000';
        $dayEarnings = CarefreeDividendAmountLog::getInstance()->where($where)->sum('amount') ?: '0.0000';
        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);

        $field = [
            'SUM(if(status=1,amount,0)) as total',
            'SUM(if(status=2,amount,0)) as exchange_red',
        ];
        $red = CarefreeRedAmountLog::getInstance()->field($field)->where('user_id',$this->userinfo->id)->find();

        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')],
        ];
        $dayRed = CarefreeRedAmountLog::getInstance()->where($where)->sum('amount') ?: '0.0000';
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',2],
        ];
        $totalPay = CarefreeDividendAmountLog::getInstance()->where($where)->sum('amount') ?: '0.0000';
        $currentScore = $finance['score'] > 0 ? $finance['score'] : $finance['sendScore'];
        return [
            'dayRed' => bcadd($dayRed,0,4), //今日分红红包
            'currentRed' => $finance['redPacket'] ?? '0.0000', //当前红包
            'totalRed' => $red['total'] ?? '0.0000', //总红包
            'exchangeRed' => $red['exchangeRed'] ?? '0.0000', //已兑换红包
            'deduction' => $finance['deduction'] ?? '0.0000', //当前抵扣金

            'dayScore' => bcadd($dayScore,0,4), //今日分红积分
            'totalScore' => $finance['allScore'], //总分红积分

            'currentEarnings' => $finance['earnings'] ?? '0.0000', //当前收益
            'dayEarnings' => bcadd($dayEarnings,0,4), //今日收益
            'totalEarnings' => $finance['allEarnings'] ?? '0.0000', //累计收益
            'totalPay' => bcadd($totalPay,0,4) ?? '0.0000', //累计支出
            'currentScore' => $currentScore, //当前分红积分
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function scoreLog($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if ($logType === 'add_all') {
            $where[] = ['status', '=', 1];
        } elseif ($logType === 'reduce_all') {
            $where[] = ['status', '=', 2];
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }

        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);
        $logList = CarefreeScoreAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $logTypeArr = ['change' => '积分分红','add' => '增加分红积分'];
        $arr = [];
        foreach ($logList as $v) {
            $v['name'] = $logTypeArr[$v['logType']] ?? '';
            $arr[$v['days']][] = $v;
        }

        $logTypeList =  [
            ['key' => '', 'name' => '全部'],
            ['key' => 'add_all', 'name' => '收入'],
            ['key' => 'reduce_all', 'name' => '支出'],
        ];
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')]
        ];
        $dayAmount = CarefreeScoreAmountLog::getInstance()
            ->where($where)
            ->sum('amount') ?: '0.0000';
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',2],
        ];
        $expend = CarefreeScoreAmountLog::getInstance()
            ->where($where)
            ->sum('amount') ?: '0.0000';
        return [
            'typeArr' => $logTypeList,
            'rows' => $arr,
            'amount' => bcadd($finance['score'],$finance['sendScore'],4) ?? '0.0000', //当前
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日分红收益
            'income' => $finance['allScore'] ?? '0.0000', // 总分红积分
            'expend' => bcsub($finance['allScore'],$finance['score']+$finance['sendScore'],4), //已分红积分
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function redLog($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if ($logType === 'add_all') {
            $where[] = ['status', '=', 1];
        } elseif ($logType === 'reduce_all') {
            $where[] = ['status', '=', 2];
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }

        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);
        $logList = CarefreeRedAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }

        $logTypeArr = ['change' => '红包兑换','add' => '积分分红'];
        $arr = [];
        foreach ($logList as $v) {
            $v['name'] = $logTypeArr[$v['logType']] ?? '';
            $arr[$v['days']][] = $v;
        }

        $logTypeList =  [
            ['key' => '', 'name' => '全部'],
            ['key' => 'add_all', 'name' => '收入'],
            ['key' => 'reduce_all', 'name' => '支出'],
        ];
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')]
        ];
        $dayAmount = CarefreeRedAmountLog::getInstance()
            ->where($where)
            ->sum('amount') ?: '0.0000';

        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')]
        ];
        return [
            'typeArr' => $logTypeList,
            'rows' => $arr,
            'amount' => $finance['redPacket'] ?? '0.0000', //当前
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日分红红包
            'income' => $finance['allRedPacket'] ?? '0.0000', // 总分红红包
            'expend' => bcsub($finance['allRedPacket'],$finance['redPacket'],4), //已兑换红包
        ];
    }


    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function dividendLog($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];
        if (!empty($logType)) {
            if (!in_array($logType, ['add_all', 'reduce_all'])) {
                if($logType == 'agency_earnings'){
                    $where[] = ['log_type', 'in', ['province_earnings','city_earnings','area_earnings']];
                }else{
                    $where[] = ['log_type', '=', $logType];
                }
            } else {
                if ($logType == 'add_all') {
                    $where[] = ['status', '=', 1];
                } else {
                    $where[] = ['status', '=', 2];
                }
            }
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }

        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);
        $logList = CarefreeDividendAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $arr = [];
        foreach ($logList as $v) {
            if(in_array($v['logType'],['province_earnings','city_earnings','area_earnings'])){
                $v['logType'] = 'agency_earnings';
            }
            $arr[$v['days']][] = $v;
        }

        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')]
        ];
        $dayAmount = CarefreeDividendAmountLog::getInstance()
            ->where($where)
            ->sum('amount') ?: '0.00';
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
        ];
        $income = CarefreeDividendAmountLog::getInstance()
            ->where($where)
            ->sum('amount') ?: '0.00';
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',2],
        ];
        $expend = CarefreeDividendAmountLog::getInstance()
            ->where($where)
            ->sum('amount') ?: 0;
        return [
            'typeArr' => $this->logTypeData(),
            'rows' => $arr,
            'amount' => $finance['earnings'] ?? '0.0000', //当前
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日分红红包
            'income' => bcadd($income, 0, 4), // 总分红红包
            'expend' => bcadd($expend,0,4) //已兑换红包
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function speedLog($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if ($logType === 'add_all') {
            $where[] = ['status', '=', 1];
        } elseif ($logType === 'reduce_all') {
            $where[] = ['status', '=', 2];
        }

        /*if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }*/

        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);

        $logList = CarefreeSpeedAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }

        $logTypeArr = ['change' => '降低速度','add' => '提升速度'];
        $arr = [];
        foreach ($logList as $v) {
            $v['name'] = $logTypeArr[$v['logType']] ?? '';
            $arr[$v['days']][] = $v;
        }
        $logTypeList =  [
            ['key' => '', 'name' => '全部'],
            ['key' => 'add_all', 'name' => '收入'],
            ['key' => 'reduce_all', 'name' => '支出'],
        ];
        /*$config = CarefreeCache::getKeyData('carefree','base');
        $rate = $config['base_rate'] ?? 0;
        $where = [
            ['user_id','=',$this->userinfo->id],
            ['speed_rate','<=',0]
        ];
        CarefreeMemberFinance::getInstance()->where($where)->update(['speed_rate' => $rate]);
        */
        return [
            'typeArr' => $logTypeList,
            'rows' => $arr,
            'amount' => $finance['speedRate'] ?? '0.00', //当前
            //'baseSpeedRate' => !empty($config['base_rate']) ? bcadd($config['base_rate'],0,2) : '0.00', //基础加速
        ];
    }

    public function logTypeData(): array
    {
        return [
            [
                'name' => '收入',
                'list' => [
                    ['key' => 'add_all', 'name' => '全部'],
                    ['key' => 'direct_earnings', 'name' => '直推收益'],
                    ['key' => 'partner_earnings', 'name' => '社区合伙人收益'],
                    ['key' => 'ping_service_earnings', 'name' => '平级服务商收益'],
                    ['key' => 'service_earnings', 'name' => '服务商收益'],
                    ['key' => 'business_earnings', 'name' => '事业部收益'],
                    ['key' => 'agency_earnings', 'name' => '代理收益'],
                ],
            ],
            [
                'name' => '支出',
                'list' => [
                    ['key' => 'reduce_all', 'name' => '全部'],
                    ['key' => 'change', 'name' => '兑现到余额'],
                ],
            ],
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function deductionLog($startAt, $endAt, $logType, $page, $pageSize): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
        ];

        if ($logType === 'add_all') {
            $where[] = ['status', '=', 1];
        } elseif ($logType === 'reduce_all') {
            $where[] = ['status', '=', 2];
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            $sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            $sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            $where[] = ['create_at', '>=', $sevenDaysAgo];
        }

        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);
        $logList = CarefreeDeductionAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }

        $logTypeArr = ['change' => '抵扣券使用','add' => '增加抵扣券','buy' => '消费订单抵扣'];
        $arr = [];
        foreach ($logList as $v) {
            $v['name'] = $logTypeArr[$v['logType']] ?? '';
            $arr[$v['days']][] = $v;
        }

        $where = [
            ['user_id','=',$this->userinfo->id],
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')]
        ];
        $dayAmount = CarefreeDeductionAmountLog::getInstance()
            ->where($where)
            ->sum('amount') ?: '0.00';

        $logTypeList =  [
            ['key' => '', 'name' => '全部'],
            ['key' => 'add_all', 'name' => '收入'],
            ['key' => 'reduce_all', 'name' => '支出'],
        ];
        return [
            'typeArr' => $logTypeList,
            'rows' => $arr,
            'amount' => $finance['deduction'] ?? '0.0000', //当前
            'dayAmount' => bcadd($dayAmount, 0, 4), //今日
            'income' => $finance['allDeduction'] ?? '0.0000', // 总抵扣金
            'expend' => bcsub($finance['allDeduction'],$finance['deduction'],4), //已使用抵扣金
        ];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function withdraw($payPassword, $amount, $type): bool
    {
        if (!RedLock::getInstance()->lock('withdrawCarefree_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        if (!in_array($type, [1, 2])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if (empty($payPassword) || $amount < 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $account = MemberService::getInstance()->account($this->userinfo->id);
        if (empty($account)) {
            CommonUtil::throwException(ErrorConst::NO_PAY_PASSWORD_ERROR, ErrorConst::NO_PAY_PASSWORD_ERROR_MSG);
        }

        //验证支付密码
        if ($account['payPwd'] != $payPassword) {
            CommonUtil::throwException(ErrorConst::PAY_PASSWORD_ERROR, ErrorConst::PAY_PASSWORD_ERROR_MSG);
        }

        $config = CarefreeCache::getKeyData('carefree','withdraw');
        /*if(!isset($config['switch']) || $config['switch'] != 1){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '提现已关闭');
        }*/
        if($type == 1){
            if(!isset($config['red_withdraw_switch']) || $config['red_withdraw_switch'] != 1){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '提现已关闭');
            }

            if($config['red_type'] == 0){
                if($amount <= $config['red_gt']){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '提现要大于'.$config['red_gt'].'元');
                }
            }else{
                //100的整数
                /*if($amount != $config['red_whole']){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '单笔只能提现'.$config['red_whole'].'元');
                }*/
                $checkAmount = bcmod($amount,100,2);
                if($checkAmount != 0){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '只能整百提现');
                }
            }

            $where = [
                ['user_id','=',$this->userinfo->id],
                ['type','=',$type],
                ['status','in',[0,1]],
                ['create_at','>=',date('Y-m-d')]
            ];
            $count = CarefreeWithdraw::getInstance()->where($where)->count();
            if($count >= $config['red_count']){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '超过提现次数');
            }
        }else{
            if(!isset($config['earnings_withdraw_switch']) || $config['earnings_withdraw_switch'] != 1){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '提现已关闭');
            }

            if($config['earnings_type'] == 0){
                if($amount <= $config['earnings_gt']){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '提现要大于'.$config['earnings_gt'].'元');
                }
            }else{
                /*if($amount != $config['earnings_whole']){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '单笔只能提现'.$config['earnings_whole'].'元');
                }*/
                $checkAmount = bcmod($amount,100,2);
                if($checkAmount != 0){
                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '只能整百提现');
                }
            }

            $where = [
                ['user_id','=',$this->userinfo->id],
                ['type','=',$type],
                ['status','in',[0,1]],
                ['create_at','>=',date('Y-m-d')]
            ];
            $count = CarefreeWithdraw::getInstance()->where($where)->count();
            if($count >= $config['earnings_count']){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '超过提现次数');
            }
        }

        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);
        $arr = [
            1 => $finance['redPacket'],
            2 => $finance['earnings'],
        ];
        $financeMoney = $arr[$type];
        if ($financeMoney < $amount) {
            CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
        }

        $return = CarefreeInfoService::getInstance()->withdraw($this->userinfo->id, $amount, $type);
        if (!$return) {
            CommonUtil::throwException(ErrorConst::WITHDRAW_ERROR, ErrorConst::WITHDRAW_ERROR_MSG);
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function withdrawList($type, $page, $pageSize): array
    {
        $where = [
            'user_id' => $this->userinfo->id,
            'type' => $type,
        ];
        $list = CarefreeWithdraw::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();
        $list = empty($list) ? [] : $list->toArray();

        $withdraw = CarefreeWithdraw::getInstance()
            ->field('sum(amount) as all_withdraw,
            sum(if(status=1,amount,0)) as success_withdraw,
            sum(if(status=1,charge,0)) as charge_withdraw')
            ->where($where)
            ->find();

        return [
            'rows' => $list,
            'allWithdraw' => bcadd($withdraw['allWithdraw'], 0, 4),
            'successWithdraw' => bcadd($withdraw['successWithdraw'], 0, 4),
            'chargeWithdraw' => bcadd($withdraw['chargeWithdraw'], 0, 4),
        ];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function withdrawInfo($type): array
    {
        if (!in_array($type, [1, 2])) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $finance = CarefreeInfoService::getInstance()->finance($this->userinfo->id);
        $config = CarefreeCache::getKeyData('carefree','withdraw');
        if($type == 1){
            $fee = $config['red_fee'] ?? 0;
            $remark = $config['red_remark'];
            $money = $finance['redPacket'];
            $deductionRate = $config['red_rep_rate'];
        }else{
            $fee = $config['earnings_fee'] ?? 0;
            $remark = $config['earnings_remark'];
            $money = $finance['earnings'];
            $deductionRate = $config['earnings_rep_rate'];
        }

        return ['remark' => $remark, 'fee' => $fee, 'deductionRate' => $deductionRate,'money' => $money];
    }

    public function switch(): array
    {
        $config = CarefreeCache::getKeyData('carefree','base');
        return ['switch' => $config['switch'] ?? 0];
    }

    public function isShowPool(): array
    {
        $config = CarefreeCache::getKeyData('carefree','base');
        return ['isShowPool' => $config['is_show_pool'] ?? 0];
    }

    public function pool(): array
    {
        $where = [
            ['status','=',1],
            ['create_at','>=',date('Y-m-d')]
        ];
        $today = CarefreeProfitPoolLog::getInstance()->where($where)->sum('amount') ?: 0;

        $list = [];
        for($i=1;$i<=7;$i++) {
            $start = date('Y-m-d', strtotime('+' . ($i - 7) . ' days'));
            $end = $start.' 23:59:59';
            $where = [
                ['status','=',1],
                ['create_at','between',[$start,$end]]
            ];
            $num = CarefreeProfitPoolLog::getInstance()
                ->where($where)
                ->sum('amount') ?: '0.00';
            $num = bcadd($num,0,2);
            $list['date'][] = date('m-d',strtotime($start));
            $list['num'][] = $num;
        }

        return ['today' => bcadd($today,0,4), 'date' => $list['date'],'num' => $list['num']];
    }

}
